<?php

namespace app\api\model;

use think\facade\Db;
use app\common\model\FinanceStat;

class Movie
{
    private $error = '';

    /**
     * 充值成功回调
     */
    public function handleSuccess($payLog)
    {
        Db::name('movie_pay_log')
            ->where('id', $payLog['id'])
            ->update([
                'status' => 2,
                'trade_no' => $payLog['trade_no'],
                'real_pay_price' => $payLog['real_pay_price'],
            ]);
        $orderUpdate = [
            'status' => 2,
        ];
        if (SETTLE_TYPE_PREPAY == $payLog['settle_type']) {
            // 如果是预付，需要判断代理商账户余额
            $balance = Db::name('agent')
                ->where('id', $payLog['agent_id'])
                ->value('balance');
            if (empty($balance) || $balance < $payLog['amount']) {
                $orderUpdate['supplier_status'] = -1;
                $orderUpdate['remark'] = '账户余额不足';
            } else {
                Db::name('agent')
                    ->where('id', $payLog['agent_id'])
                    ->dec('balance', $payLog['amount'])
                    ->update([
                        'balance_last_updated_at' => date('Y-m-d H:i:s'),
                    ]);
                $id = Db::name('movie_order')
                    ->where('order_id', $payLog['order_id'])
                    ->value('id');
                Db::name('agent_balance_log')
                    ->insert([
                        'agent_id' => $payLog['agent_id'],
                        'type' => BALANCE_FILM_EXPENSE,
                        'amount' => -$payLog['amount'],
                        'old_balance' => $balance,
                        'new_balance' => $balance - $payLog['amount'],
                        'remark' => '购买影票：'.fen2yuan($payLog['amount']).'元。订单号：'.$payLog['order_id'],
                        'quote_id' => $id,
                        'trade_no' => $payLog['order_id'],
                    ]);
            }
        }

        Db::name('taototo_order')
            ->where('order_id', $payLog['order_id'])
            ->update([
                'status' => 2,
            ]);
            
        Db::name('movie_order')
            ->where('order_id', $payLog['order_id'])
            ->update($orderUpdate);

        Db::name('base_supplier')
            ->where('id', $payLog['supplier_id'])
            ->inc('order_count', 1)
            ->update();
    }

    public function getError()
    {
        return $this->error;
    }
}
